<?php
/**
 * Created by PhpStorm.
 *
 * Author : Traveler.
 * Time   : 2020/2/21 13:29
 * Company: Inner Mongolia Zhengzhi Network Technology Co., Ltd
 */

namespace app\admin\controller;


use app\admin\BaseController;
use app\admin\model\Staff as StaffModel;
use app\admin\model\StaffRole as StaffRoleModel;
use app\admin\model\Config as ConfigModel;
use think\captcha\facade\Captcha;
use think\facade\Session;
use think\facade\View;

class Login extends BaseController
{
    /**
     * 用户登录
     * @return string|\think\response\Json|\think\response\Redirect
     */
    public function index()
    {
        // Session存在，则直接跳转至后台首页
        if (Session::has('admin_id')) {
            return redirect((string)url('Index/index'));
        }

        // 提交
        if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证数据
            $validate = $this->validate($data, 'Staff.login');
            if (true !== $validate) {
                return $this->error($validate);
            }

            // 验证登录
            $staff = StaffModel::where('cellphone|email', $data['username'])->with(['dept', 'role'])->find();
            if (!$staff) {
                return $this->error('手机号/邮箱不存在');
            }
            if (!ibms_password_verify($data['password'], $staff['password'])) {
                return $this->error('密码不正确');
            }
            if (0 == $staff['status']) {
                return $this->error('用户已被禁用');
            }

            // 登录成功
            // 设置Session
            Session::set('admin_id', $staff['id']);
            Session::set('admin_info', $staff->toArray());
            Session::set('admin_flag', StaffRoleModel::getRoleFlag($staff['role']['nodes']));

            // 登录信息
            $staff['login_count'] += 1;
            $staff['login_ip'] = $this->request->ip();
            $staff['login_time'] = time();

            // 保存登录信息
            $staff->save();

            return $this->success('登录成功');
        }

        // 渲染页面：用户登录
        $config = ConfigModel::getConfigByGroup(['website']);
        return View::assign('config', $config)->fetch();
    }

    /**
     * 用户退出
     * @return \think\response\Redirect
     */
    public function logout()
    {
        // 删除Session
        Session::delete('admin_id');
        Session::delete('admin_info');
        Session::delete('admin_flag');

        return redirect((string)url('Login/index'));
    }

    /**
     * 验证码
     * @return \think\Response
     */
    public function captcha()
    {
        return Captcha::create('ibms');
    }
}